package controller

import (
	"fmt"
	"log"
	"mumu_stock_trad/model"
	"mumu_stock_trad/util"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// GetStockData 获取股票数据的控制器
func GetStockData(c *gin.Context) {
	symbol := c.Param("symbol")

	// 调用 Util 中的函数获取股票数据
	stockData, err := util.FetchStockData(symbol)
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
		return
	}

	if 1 == 1 {
		// 将股票数据存储到 MySQL 数据库
		err = model.SaveStockData(stockData)
		if err != nil {
			log.Printf("Error saving stock data: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
			return
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    stockData,
	})
}

func GetStockDataQt(c *gin.Context) {
	symbol := c.Param("symbol")

	// 调用 Util 中的函数获取股票数据
	stockData, err := util.FetchStockDataQt(symbol)
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
		return
	}

	if 1 == 1 {
		// 将股票数据存储到 MySQL 数据库
		err = model.SaveStockDataQT(stockData)
		if err != nil {
			log.Printf("Error saving stock data: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
			return
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    stockData,
	})
}

func UpdateStockQtAll() {
	page := 1
	pageSize := 1000000
	stocks, err := model.GetStockListPage(page, pageSize)
	if err != nil {
		log.Printf("Error saving stock data: %v", err)
		return
	}
	i := 1
	for _, li := range stocks {
		time.Sleep(time.Millisecond * 3)
		i++
		if i > 3000 {
			i = 0
			time.Sleep(time.Second * 3)
		}
		go Save(fmt.Sprintf("%s%s", li.Market, li.Code))
	}
}

func GetStockQtAlll(c *gin.Context) {
	// 获取第一页，每页显示 10 条数据
	page := 1
	pageSize := 22
	stocks, err := model.GetStockListPage(page, pageSize)
	if err != nil {
		log.Printf("Error saving stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
		return
	}

	codeStr := ""
	i := 1
	for _, li := range stocks {
		time.Sleep(time.Millisecond * 3)
		i++
		if i > 3000 {
			i = 0
			time.Sleep(time.Second * 3)
		}
		if codeStr == "" {
			codeStr = fmt.Sprintf("%s%s", li.Market, li.Code)
		} else {
			codeStr = codeStr + "," + fmt.Sprintf("%s%s", li.Market, li.Code)
		}
		if i == 20 {
			i = 1
			data, err := SaveBatch(codeStr)
			// 返回成功响应
			c.JSON(http.StatusOK, gin.H{
				"message": err.Error(),
				"data":    data,
			})
			return
			codeStr = ""
		}
		i++
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    stocks,
	})
}

func GetStockQtAll(c *gin.Context) {
	// 获取第一页，每页显示 10 条数据
	page := 1
	pageSize := 1000000
	stocks, err := model.GetStockListPage(page, pageSize)
	if err != nil {
		log.Printf("Error saving stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
		return
	}

	i := 1
	for _, li := range stocks {
		time.Sleep(time.Millisecond * 3)
		i++
		if i > 3000 {
			i = 0
			time.Sleep(time.Second * 3)
		}
		go Save(fmt.Sprintf("%s%s", li.Market, li.Code))
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    stocks,
	})
}

func SaveBatch(code string) ([]model.StockDataQT, error) {
	stockData, err := util.FetchStockDataQtAll(code)
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		return nil, err
	}

	date := time.Now().Format("2006-01-02") // 格式化为 "年-月-日"
	date = "2024-07-17"
	for k, _ := range stockData {
		stockData[k].Date = date
	}

	err = model.BatchInsertStockDataQT(stockData)

	fmt.Println(err.Error())

	return stockData, err

	// for _, v := range stockData {
	// 	// 将股票数据存储到 MySQL 数据库
	// 	err = model.SaveStockDataQT(v)
	// 	if err != nil {
	// 		log.Printf("Error saving stock data: %v", err)
	// 		return
	// 	}
	// }
}

func Save(code string) {
	stockData, err := util.FetchStockDataQt(code)
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		return
	}
	// 将股票数据存储到 MySQL 数据库
	err = model.SaveStockDataQT(stockData)
	if err != nil {
		log.Printf("Error saving stock data: %v", err)
		return
	}
}

func GetStockDataList(c *gin.Context) {

	// 调用 Util 中的函数获取股票数据
	stockData, response, _, err := util.FetchStockList(1, "")
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
		return
	}

	if 1 == 1 {
		for _, val := range stockData {
			// 将股票数据存储到 MySQL 数据库
			err = val.SaveStockList()
			if err != nil {
				log.Printf("Error saving stock data: %v", err)
				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
				return
			}
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    response,
	})
}

func GetCategory(c *gin.Context) {
	data, err := util.GetCategory()
	if err != nil {
		log.Printf("Error fetching stock data: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
		return
	}

	if 1 == 1 {
		model.SaveCategory(data)
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Stock data saved successfully",
		"data":    data,
	})
}

func GetStockListByCategory(c *gin.Context) {
	data, err := model.GetAllCategories()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	stockData := []model.StockList{}

	for _, v := range data {
		if v.Code != "cyb" && v.Code != "" {
			page := 1
			_, _, allPage, err := util.FetchStockList(page, v.Code)
			if err != nil {
				log.Printf("Error fetching stock data: %v", err)
				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
				return
			}
			for i := 1; i <= allPage; i++ {
				time.Sleep(time.Millisecond * 100)
				stockData, _, _, err = util.FetchStockList(i, v.Code)
				if err != nil {
					log.Printf("Error fetching stock data: %v", err)
					c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch stock data"})
					return
				}
				for _, val := range stockData {
					// 将股票数据存储到 MySQL 数据库
					err = val.SaveStockList()
					if err != nil {
						log.Printf("Error saving stock data: %v", err)
						c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save stock data"})
						return
					}
				}
			}
		}
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message": "Get successfully",
		"data":    data,
	})
}
